﻿using System;
using System.Diagnostics;
using System.Text;

namespace SimpleStringEncryption
{
    class Program
    {
        static void Main(string[] args)
        {
            var strPass = StrToPass("Hello World!");
            var st = Stopwatch.StartNew();
            Console.WriteLine($"加密字符: {strPass}");
            Console.WriteLine($"解密字符: {PassToStr(strPass)}");
            st.Stop();
            Console.WriteLine(st.Elapsed);
            Console.ReadKey();
        }

        static string StrToPass(string str)
        {
            var result = new StringBuilder();

            var rnd = new Random();
            var key = rnd.Next() % 100;
            result.Append(string.Format("{0:X2}", key));
            for (var i = 0; i < str.Length; i++)
            {
                var hex = Convert.ToByte(str[i]) ^ (key + i + 1);
                var abyte = (hex & 0xf0) >> 4;
                var abyte1 = (hex & 0x0f) << 4;
                abyte = abyte1 | abyte;

                result.Append(string.Format("{0:X2}", abyte));
            }

            return result.ToString();
        }

        static string PassToStr(string strPass)
        {
            var result = new StringBuilder();

            var key = Convert.ToInt32(strPass.Substring(0, 2), 16);
            var j = 1;
            for (var i = 2; i < strPass.Length; i += 2, j++)
            {
                var tmpBuf = strPass.Substring(i, 2);
                var hex = Convert.ToInt32(tmpBuf, 16);
                var abyte = (hex & 0xf0) >> 4;
                var abyte1 = (hex & 0x0f) << 4;
                result.Append(Convert.ToChar((abyte1 | abyte) ^ (key + j)));
            }

            return result.ToString();
        }
    }
}
